package com.aptemo.webetek.server.handlers;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.aptemo.webetek.client.commands.Action;
import com.aptemo.webetek.client.commands.impl.CreateTeamAction;
import com.aptemo.webetek.client.enums.EnumTeamStatus;
import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.client.exceptions.WebetekLoginException;
import com.aptemo.webetek.server.datastore.DataStoreAPI;
import com.aptemo.webetek.shared.TeamBean;

public class CreateTeamHandler
		extends ActionHandler<CreateTeamAction, TeamBean>
{

	public CreateTeamHandler(DataStoreAPI dataService)
	{
		super(dataService);
	}

	@Override
	public Class<? extends Action<?>> getActionType()
	{
		return CreateTeamAction.class;
	}

	@Override
	public TeamBean invoke(CreateTeamAction action) throws BackendException, WebetekLoginException
	{
		utils.checkLogin();
		// utils.checkAdmin();

		String ownerEmail = action.getBean().getOwnerEmail();
		String userEmail = userService.getCurrentUser().getEmail();

		if (ownerEmail == null || ownerEmail.isEmpty())
		{
			ownerEmail = userEmail;
		}

		TeamBean team = dataService.createTeam(action.getBean().getName(), action.getBean().getDescription(), action.getBean().getTeamRules(), ownerEmail,
				action.getBean().isPublic(), action.getBean().isNotifications(), action.getBean().getMinStake(), action.getBean().getMaxStake());

		String subject = "[Webetek Admin] New team request...";
		String content = "User " + userEmail + " requests new Team.\n";
		content += "\nId: " + team.getId();
		content += "\nOwner: " + team.getOwnerEmail();
		content += "\nTitle: " + team.getName();
		content += "\nDescription: " + team.getDescription();

		String path = this.getServletUrl();
		String link = path + "/webetek/commandService?actionId=com.aptemo.webetek.client.commands.impl.ModifyTeamStatusAction&json=";
		try
		{
			link += URLEncoder.encode("{teamId:\"" + team.getId() + "\",status:\"" + EnumTeamStatus.ACTIVE.toString() + "\"}", "UTF-8");
		}
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		content += "\n";
		content += "\nApprove: " + link;
		content += "\n";

		// webetek/commandService?actionId=com.aptemo.webetek.client.commands.impl.ModifyTeamStatusAction&json={teamId:"agd3ZWJldGVrchALEglVc2VyR3JvdXAYwwUM",status:"ACTIVE"}

		createEmailSenderTask("", WEBETEK_ADMIN_EMAIL, "", subject, content);

		return team;

	}

}
